import st from "./showtoast.js";
import {
	HTTP_REQUEST_URL,
} from "../config/app.js";


/**
 * 需要保存token的请求
 */
export let post2 = (url, data = {}) => {
	uni.showLoading({
		title: ""
	})
	let promise = new Promise((success, fail) => {
		uni.request({
			url: HTTP_REQUEST_URL + url,
			method: "POST",
			header: {
			},
			data: data,
			success: res => {
				let model = res.data
				if (model.code == 1) {
					success(model)
				} else {
					st.show(model.msg)
					fail(model)
				}
			},
			fail: res => {
				fail(res.data)
			},
			complete: res => {
				uni.hideLoading()
			}
		})
	})
	return promise
}

/**
 * 需要请求头的
 */
export let post = (url, data = {}) => {
	uni.showLoading({
		title: ""
	})
	let promise = new Promise((success, fail) => {
		uni.request({
			url: HTTP_REQUEST_URL + url,
			method: "POST",
			header: {
				token: uni.getStorageSync("token") || ""
			},
			data: data,
			success: res => {
				let model = res.data
				if (model.code == 1) {
					success(model)
				} else {
					st.show(model.msg)
					fail(model)
				}
			},
			fail: res => {
				fail(res.data)
			},
			complete: res => {
				uni.hideLoading()
				uni.stopPullDownRefresh()
			}
		})
	})
	return promise
}

/**
 * get请求
 */
/**
 * 需要请求头的
 */
export let get = (url, data = {}) => {
	uni.showLoading({
		title: ""
	})
	let promise = new Promise((success, fail) => {
		uni.request({
			url: HTTP_REQUEST_URL + url,
			method: "GET",
			header: {
				token: uni.getStorageSync("token") || ""
			},
			data: data,
			success: res => {
				let model = res.data
				if (model.code == 1) {
					success(model)
				} else {
					st.show(model.msg)
					fail(model)
				}
			},
			fail: res => {
				fail(res.data)
			},
			complete: res => {
				uni.hideLoading()
				uni.stopPullDownRefresh()
			}
		})
	})
	return promise
}

/**
 * 上传图片
 */
export let upload = (file) => {
	uni.showLoading({
		title: ""
	})
	let promise = new Promise((success, fail) => {
		uni.uploadFile({
			filePath: file,
			name: "file",
			header: {
				token: uni.getStorageSync("token") || ""
			},
			url: HTTP_REQUEST_URL + "common/upload",
			success(res) {
				let data = JSON.parse(res.data)
				if (data.code == 1) {
					success(data)
				} else {
					st.show(data.msg)
					fail(data)
				}
			},
			fail: res => {
				fail(res)
			},
			complete: () => {
				uni.hideLoading()
			}
		})
	})
	return promise
}

module.exports = {
	get,
	post,
	post2,
	upload
}